package com.xhj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhj.entity.User;
import com.xhj.securityEntity.SecurityUser;
import com.xhj.service.PermissionService;
import com.xhj.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userService.getOne(queryWrapper);
        if (user == null) throw new RuntimeException("用户名不存在！");
        com.xhj.securityEntity.User user1 = new com.xhj.securityEntity.User();
        BeanUtils.copyProperties(user,user1);

        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        SecurityUser securityUser = new SecurityUser(user1);
        securityUser.setPermissionValueList(authorities);

        return securityUser;
    }
}
